import Skype4Py
from sendEmail import SkypeSendEmail
from pysqlite2 import dbapi2 as sqlite
from properties import Properties
import time
from webstring import Template

skype = Skype4Py.Skype()
skype.FriendlyName = 'Sync_chat_history'
skype.Attach()

chats = skype.Chats

con = sqlite.connect('skypesync')
p = Properties()
p.load(open('skype.properties'))
	
def makeChatBody(msg_list):
	html=''
	cur = con.cursor()
	for m in msg_list:
		strId=str(m.Id)
		
		cur.execute('SELECT * FROM messages WHERE messageid="'+strId+'"')
		row=cur.fetchall()
		
		if len(row) != 0:
			continue

		user=m.Sender
		username=user.FullName
		
		dateTime=m.Datetime.isoformat(' ')
		body=m.Body
			
		fullMessage='['+dateTime+']: '+ username +': ' + body + '\n'
		html+=fullMessage
	return html	
# Sorting based on timestamps, with custom compare fct
def message_timestamp_cmp(x, y):
	return int(x.Timestamp - y.Timestamp)

def saveMessagesIds(msg_list):
	cur = con.cursor()
	for m in msg_list:
		strId=str(m.Id)
		cur.execute('SELECT * FROM messages WHERE messageid="'+strId+'"')
		row=cur.fetchall()
		if len(row) != 0:
			continue

		cur.execute('INSERT INTO messages (messageid) VALUES("'+strId+'")')
		con.commit()		


for c in chats:
	# c.Messages is a tuple, to be able to sort it,
	# convert it into a list
	msg_list = list(c.Messages)
	#dialogPartner=c.DialogPartner
	dialogPartner=''
	    
	members=c.Members
	#my skype full name
	me=p['skypeFullName']
	    
	for m in members:
		partner=m.FullName
		if partner != me:
			dialogPartner=dialogPartner+' '+partner
		#print dialogPartner
		
	# why are timestamps float and not int in Skype4Py?
	msg_list.sort(message_timestamp_cmp)
	
	html=makeChatBody(msg_list)
	if len(html) == 0:
		continue

	messageIntro=''
	dateTime=''
	username=''
	for m in msg_list:
		messageIntro=m.Body[0:30]+'...'
		dateTime=m.Datetime.isoformat(' ')
		user=m.Sender
		username=user.FullName		
		break
	
	flg=1	
	skypeEmail=SkypeSendEmail()
	#skypeEmail.send_email(dialogPartner, dateTime, messageIntro, html , username)
	while flg==1:
		try:
			skypeEmail.send_email(dialogPartner, dateTime, messageIntro, html , username)
			flg=0
		except:
			time.sleep(20)
			
	time.sleep(200)
	saveMessagesIds(msg_list)